package com.chenglu.android.mine.address;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chenglu.android.R;
import com.chenglu.android.common.base.BaseActionBarActivity;
import com.chenglu.android.common.utils.BaseDialog;
import com.chenglu.android.common.utils.EdittextUtils;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.SPUtils;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.common.utils.Utils;
import com.chenglu.android.mine.address.mvp.contract.AddressManagerContract;
import com.chenglu.android.mine.address.mvp.presenter.AddressManagerPresenter;
import com.chenglu.android.mine.bean.AddressListBean;
import com.chenglu.android.mine.bean.AddressSubmitBean;
import com.chenglu.android.mine.bean.AddressTreeBean;
import com.chenglu.android.mine.bean.CommonDataBean;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopupext.listener.CityPickerListener;
import com.lxj.xpopupext.popup.CityPickerPopup;
import com.suke.widget.SwitchButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: lyj
 * @Created: by Copyright 2023 3 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description：
 */
public class AddressEditActivity extends BaseActionBarActivity<AddressManagerPresenter> implements AddressManagerContract.View {

    public static final String ADDRESSDATA = "addressData";
    @BindView(R.id.et_address_contract)
    EditText etAddressContract;
    @BindView(R.id.iv_clear_contract)
    ImageView ivClearContract;
    @BindView(R.id.et_address_phone)
    EditText etAddressPhone;
    @BindView(R.id.iv_clear_phone)
    ImageView ivClearPhone;
    @BindView(R.id.tv_address_dis)
    TextView tvAddressDis;
    @BindView(R.id.iv_clear_dis)
    ImageView ivClearDis;
    @BindView(R.id.et_address_detail)
    EditText etAddressDetail;
    @BindView(R.id.iv_clear_detail)
    ImageView ivClearDetail;
    @BindView(R.id.cb_address)
    SwitchButton switchButton;
    @BindView(R.id.btn_address_save)
    Button btnAddressSave;
    @BindView(R.id.ll_address_city)
    LinearLayout llAddressCity;
    @BindView(R.id.ll_loading_data)
    LinearLayout llLoadingData;
    @BindView(R.id.tv_loading_data)
    TextView tvLoadingData;
    @BindView(R.id.ll_loading_no_data)
    LinearLayout llLoadingNoData;
    @BindView(R.id.rl_address_delete)
    RelativeLayout rlAddressDelete;


    private String cityName, provinceName, district;
    private String cityId, provinceId, districtId;
    private String consignee;
    private String id, userId;
    private int isDefault = 0;
    private AddressListBean.Data data;

    private int type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_address_edit;
    }

    @Override
    protected void initView() {
        mPresenter = new AddressManagerPresenter();
        mPresenter.attachView(this);

        data = (AddressListBean.Data) getIntent().getSerializableExtra(ADDRESSDATA);
        if (data != null) {
            setCenterText("编辑收货地址");

            etAddressContract.setText(data.getConsignee());
            etAddressPhone.setText(data.getMobile());
            tvAddressDis.setText(data.getCity() + " " + data.getProvince() + "  " + data.getDistrict());
            tvAddressDis.setTextColor(getResources().getColor(R.color.home_text_color));
            etAddressDetail.setText(data.getAddress());
            if (data.getIsDefault() == 1) {
                switchButton.setChecked(true);
                isDefault = 1;
            } else {
                switchButton.setChecked(false);
                isDefault = 0;
            }
            type = 101;
            rlAddressDelete.setVisibility(View.VISIBLE); //删除地址显示

        } else {
            setCenterText("添加收货地址");
            rlAddressDelete.setVisibility(View.GONE); //删除地址隐藏
            switchButton.setChecked(false);
            type = 100;
        }
        //请求所有地址
        mPresenter.getAddressTree();
        //删除按钮
        EdittextUtils.setClearImage(etAddressContract, ivClearContract);
        //删除按钮
        EdittextUtils.setClearImage(etAddressPhone, ivClearPhone);
        //删除按钮
        EdittextUtils.setClearImage(etAddressDetail, ivClearDetail);


        switchButton.isChecked();
        switchButton.toggle();     //switch state
        switchButton.toggle(true);//switch without animation
        switchButton.setShadowEffect(false);//disable shadow effect
        switchButton.setEnabled(true);//disable button
        switchButton.setEnableEffect(true);//disable the switch animation

        switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {

                //TODO do your job
                if (isChecked == true) {
                    isDefault = 1;
//                    ToastUtils.show(isDefault+"");
                } else {
                    isDefault = 0;
//                    ToastUtils.show(isDefault+"");
                }
            }
        });

    }

    @Override
    public void getAddressList(AddressListBean addressList) {


    }

    //收货地址
    @Override
    public void getAddressSubmit(AddressSubmitBean bean) {

        if (type == 101) {
            ToastUtils.show("编辑成功");
        } else {
            ToastUtils.show("新增成功");
        }
        finish();
    }


    @Override
    public void getAddressUpdate(AddressSubmitBean submitBean) {
        ToastUtils.show("编辑成功");
        finish();
    }


    /**
     * @description 地址管理匹配选择的城市
     */

    private List<AddressTreeBean.DataBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<AddressTreeBean.DataBean.ChildrenBeanX>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<AddressTreeBean.DataBean.ChildrenBeanX.ChildrenBean>>> options3Items = new ArrayList<>();

    @Override
    public void getAddressTree(AddressTreeBean treeBean) {
        LogUtils.v("treebean---" + treeBean.getData().toString());
        //添加数据
        for (int i = 0; i < treeBean.getData().size(); i++) {
            if (treeBean.getData().size() > 0) {
                options1Items.add(treeBean.getData().get(i));
            }
        }


    }


    /**
     * @description 删除地址
     */

    @Override
    public void getAddressDelete(CommonDataBean bean) {
          ToastUtils.show("删除成功");
          finish();
    }

    @Override
    public void onError(String errorMsg) {
        super.onError(errorMsg);
        isLogin = false;
        SPUtils.setBoolean("ISLOGIN", false);
        showEmptyView("暂无数据");
//        showXPopupView(context, "提示", "登录已过期,请重新登录", "登录");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);

    }


//    @Override
//    public void finish() {
//        super.finish();
    //左侧退出的动画
//        overridePendingTransition(R.anim.slide_in_from_left,R.anim.slide_out_from_right);
//    }

    @OnClick({R.id.ll_address_city, R.id.btn_address_save, R.id.rl_address_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_address_city:
                showPopCity();

                break;
            case R.id.rl_address_delete:
                BaseDialog.showDialog(mContext, "是否删除该地址", "取消", "确定", new OnConfirmListener() {
                    @Override
                    public void onConfirm() {

                        mPresenter.getAddressDelete(getToken(), data.getId());
                    }
                }, false);
                break;
            case R.id.btn_address_save:

                String contract = etAddressContract.getText().toString();
                String phone = etAddressPhone.getText().toString();
                String dis = tvAddressDis.getText().toString();
                String addressDetail = etAddressDetail.getText().toString();

                if (TextUtils.isEmpty(contract)) {
                    ToastUtils.show("请填写联系人姓名");
                    return;
                }
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.show("请填写手机号");
                    return;
                }
                if (!Utils.isMobileNO(phone)) {
                    ToastUtils.show("请输入正确手机号");
                    return;
                }
                if (dis.equals("省市区县、乡镇等")) {
                    ToastUtils.show("请选择省市区县、乡镇等");
                    return;
                }
                if (TextUtils.isEmpty(dis)) {
                    ToastUtils.show("请选择省市区县、乡镇等");
                    return;
                }
                if (TextUtils.isEmpty(addressDetail)) {
                    ToastUtils.show("请填写街道、楼牌号");
                    return;
                }
                //去保存的时候 检查地址和所在地区变化和改变 传递参数
                JSONObject jsonObject = new JSONObject();
                try {
                    //默认是编辑地址 未改动所在地区时的判断
                    if (provinceId != null && cityId != null || districtId != null) {
                        //空传0
                        if (cityId == null) {
                            jsonObject.put("cityId", 0);
                        } else {
                            // 编辑地址传的
                            jsonObject.put("cityId", cityId);
                        }
                        if (districtId == null) {
                            jsonObject.put("districtId", 0);
                        } else {
                            jsonObject.put("districtId", districtId);
                        }
                        if (provinceId == null) {
                            jsonObject.put("provinceId", 0);
                        } else {
                            jsonObject.put("provinceId", provinceId);
                        }
                        initJson(contract, phone, addressDetail, jsonObject, cityName, district, provinceName);
                        LogUtils.d("json=====" + new Gson().toJson(jsonObject));
                        //保存地址
                        String aaccessToken = SPUtils.getString("AaccessToken", "AaccessToken");
                        mPresenter.getAddressSubmit(aaccessToken, Utils.getRequestBody(jsonObject));
                    } else {
                        //空传0
                        if (cityId == null) {
                            jsonObject.put("cityId", data.getCityId());
                        } else {
                            jsonObject.put("cityId", cityId);
                        }
                        if (districtId == null) {
                            jsonObject.put("districtId", data.getDistrictId());
                        } else {
                            jsonObject.put("districtId", districtId);
                        }
                        if (provinceId == null) {
                            jsonObject.put("provinceId", data.getProvinceId());
                        } else {
                            jsonObject.put("provinceId", provinceId);
                        }

                        initJson(contract, phone, addressDetail, jsonObject,
                                data.getCity(), data.getDistrict(), data.getProvince());
                        LogUtils.d("json=====" + new Gson().toJson(jsonObject));
                        //更新地址
                        String aaccessToken = SPUtils.getString("AaccessToken", "AaccessToken");
                        mPresenter.getAddressUpdate(aaccessToken, Utils.getRequestBody(jsonObject));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void initJson(String contract, String phone, String addressDetail, JSONObject jsonObject, String cityName, String district, String provinceName) throws JSONException {
        if (type == 101) {
            jsonObject.put("userId", data.getUserId());
            jsonObject.put("id", data.getId());
        }
        jsonObject.put("consignee", contract);
        jsonObject.put("mobile", phone);
        jsonObject.put("city", cityName);
        jsonObject.put("district", district);
        jsonObject.put("province", provinceName);
        jsonObject.put("address", addressDetail);
        jsonObject.put("isDefault", isDefault);

    }


    //三省联动弹窗设置
    private void showPopCity() {

        CityPickerPopup popup = new CityPickerPopup(AddressEditActivity.this);
        popup.setCityPickerListener(new CityPickerListener() {
            @Override
            public void onCityConfirm(String province, String city, String area, View v) {

                provinceName = province;
                cityName = city;
                district = area;
                LogUtils.v("得到省份=" + provinceName + "   得到城市" + cityName + "    得到区" + district);
                //这里去匹配城市id 这里操作 youbug
                for (int i = 0; i < options1Items.size(); i++) {
                    if (province.equals(options1Items.get(i).getTitle())) {
                        provinceId = options1Items.get(i).getId();
                        if (options1Items.get(i).isHasChildren()) {
                            for (int j = 0; j < options1Items.get(i).getChildren().size(); j++) {
                                if (city.equals(options1Items.get(i).getChildren().get(j).getTitle())) {
                                    cityId = options1Items.get(i).getChildren().get(j).getId();
                                    if (options1Items.get(i).getChildren().get(j).isHasChildren()) {
                                        LogUtils.v("size:" + options1Items.get(i).getChildren().get(j).getChildren().size());
                                        for (int k = 0; k < options1Items.get(i).getChildren().get(j).getChildren().size(); k++) {
                                            if (area.equals(options1Items.get(i).getChildren().get(j).getChildren().get(k).getTitle())) {
                                                districtId = options1Items.get(i).getChildren().get(j).getChildren().get(k).getId();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }


                }
                LogUtils.v("得到省份id=" + provinceId + "   得到城市id" + cityId + "    得到区id" + districtId);
                tvAddressDis.setText(province + " " + city + "  " + area);
                tvAddressDis.setTextColor(getResources().getColor(R.color.color_333333));
//                Toast.makeText(AddressEditActivity.this, province +" - " +city+" - " +area, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCityChange(String province, String city, String area) {
//                Log.e("tag", province +" - " +city+" - " +area);
//                Toast.makeText(AddressEditActivity.this, province +" - " +city+" - " +area, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {

            }
        });
        new XPopup.Builder(AddressEditActivity.this)
                .asCustom(popup)
                .show();
    }
}
